package cn.cm.service.impl;

import cn.cm.config.OutData;
import cn.cm.dao.SysUserDao;
import cn.cm.entity.SysUser;
import cn.cm.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author shikundai
 * @date 2021/6/23
 * @time 19:55
 * @description: 用户的业务逻辑层
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserDao sysUserDao;
    @Override
    public OutData addUser(SysUser sysUser) {
        OutData outData=new OutData();

        //（1）查看数据库是否有这个名字
        QueryWrapper<SysUser> q1=new QueryWrapper<>();
        q1.eq("name",sysUser.getName());
        List<SysUser> users=sysUserDao.selectList(q1);
        if (users!=null&&users.size()>0){
            throw new RuntimeException("该用户已存在！");
        }
        //（2）插入数据操作
        //插入数据库之前对密码进行加密
        String psw=new Md5Hash(sysUser.getPassword(),"",999).toString();
        //把加密后的密码放到对象里
        sysUser.setPassword(psw);
        int out=sysUserDao.insert(sysUser);
        //对插入结果进行判断
        if (out>0){
            outData.setMsg("插入用户成功!");
        }else {
            outData.setCode(500);
            outData.setMsg("插入用户数据失败！");
        }

        return outData;
    }

    @Override
    public OutData getAllUsers() {
        OutData outData=new OutData();


        List<SysUser> users=sysUserDao.selectList(null);
        outData.setData(users);


        return outData;
    }

    @Override
    public SysUser getUserByname(String name) {
        QueryWrapper<SysUser> q1=new QueryWrapper<>();
        q1.eq("name",name);

        SysUser out=sysUserDao.selectOne(q1);
        return out;
    }
}
